const express = require('express');
const router = express.Router();
const db = require('../utils/db');

//渲染
router.post('/getTeacher', (req, res) => {
  const { search, page, count } = req.body;
  const sql = `SELECT t_id,t_name,t_tel,t_class,c_class,g_grade FROM p_teacher LEFT JOIN p_class ON p_teacher.t_class=p_class.c_id  LEFT JOIN p_grade ON p_class.c_grade=p_grade.g_id WHERE t_name LIKE '%${search}%' LIMIT ${
    (page - 1) * count
  },${count};`;
  const sql2 = `SELECT COUNT(*) AS total FROM p_teacher WHERE t_name LIKE '%${search}%';`;
  db.query(sql, (err, data) => {
    if (err) throw err;
    db.query(sql2, (err2, data2) => {
      if (err2) throw err2;
      res.send({
        error: 0,
        msg: '数据获取成功',
        data: data,
        total: data2[0].total,
      });
    });
  });
});

//班级id
router.post('/getClassId', (req, res) => {
  const sql = `SELECT c_id,c_class FROM p_class`;
  db.query(sql, (err, data) => {
    if (err) throw err;
    res.send({ error: 0, msg: '数据获取成功', data });
  });
});

//添加
router.post('/addTeacher', (req, res) => {
  const { name, tel, classId } = req.body;
  const sql = `INSERT INTO p_teacher VALUE(NULL,'${name}','${tel}',${classId})`;
  db.query(sql, (err, data) => {
    if (err) throw err;
    res.send({ error: 0, msg: '添加成功', data });
  });
});

//删除
router.post('/delTeacher', (req, res) => {
  const { id } = req.body;
  const sql = `DELETE FROM p_teacher WHERE t_id=${id};`;
  db.query(sql, (err, data) => {
    if (err) throw err;
    res.send({ error: 0, msg: '删除成功', data });
  });
});

//编辑
router.post('/editTeacher', (req, res) => {
  const { id, tel, classId } = req.body;
  const sql = `UPDATE p_teacher SET t_tel='${tel}',t_class='${classId}' WHERE t_id=${id};`;
  db.query(sql, (err, data) => {
    if (err) throw err;
    res.send({ error: 0, msg: '修改成功', data });
  });
});
module.exports = router;
